const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { VT_IMG_PARM_DIR } = require('../constants/paths');

// 递归获取所有图片文件
router.get("/vt_parm_curve_images", (req, res) => {
  const imgRootDir = "L1X/imgInfo_curve";
  const fullImgRootDir = path.join(VT_IMG_PARM_DIR, imgRootDir);
  fs.readdir(fullImgRootDir, (err, years) => {
      if (err) return res.status(500).json({ error: "无法读取主目录" });

      let monthData = {};

      years
          .filter(year => /^\d{4}$/.test(year))
          .forEach(year => {
              const yearPath = path.join(fullImgRootDir, year);
              const files = fs.readdirSync(yearPath);

              files
                  .filter(file => file.endsWith("_plot.png"))
                  .forEach(file => {
                      const match = file.match(/^(\d{4})-(\d{2})-(\d{2})_plot\.png$/);
                      if (match) {
                          const [, fileYear, month, day] = match;
                          const monthKey = `${fileYear}-${month}`;
                          if (!monthData[monthKey]) {
                              monthData[monthKey] = [];
                          }
                          monthData[monthKey].push(`${imgRootDir}/${fileYear}/${file}`);
                      }
                  });
          });

      const sortedData = Object.keys(monthData)
          .sort((a, b) => b.localeCompare(a))
          .reduce((acc, key) => {
              acc[key] = monthData[key].sort((a, b) => b.localeCompare(a));
              return acc;
          }, {});

      res.json(sortedData);
  });
});

// 获取VT观测月份
router.get("/vtmonths", (req, res) => {
  const jsonRootDir = "L1X/imgInfo";
  const fullJsonRootDir = path.join(VT_IMG_PARM_DIR, jsonRootDir);
  try {
      const years = fs.readdirSync(fullJsonRootDir).filter(year => /^\d{4}$/.test(year));
      const months = years.flatMap(year => {
          const monthDirs = fs.readdirSync(path.join(fullJsonRootDir, year))
              .map(file => file.replace(".json", "").slice(0, 7));
          return [...new Set(monthDirs)];
      }).sort().reverse();
      res.json(months);
  } catch (error) {
      res.status(500).json({ error: "Failed to fetch months." });
  }
});

// 获取某月所有的观测日
router.get("/vtdays/:month", (req, res) => {
  const jsonRootDir = "L1X/imgInfo";
  const fullJsonRootDir = path.join(VT_IMG_PARM_DIR, jsonRootDir);
  try {
      const { month } = req.params;
      const year = month.split("-")[0];
      const monthDir = path.join(fullJsonRootDir, year);
      const days = fs.readdirSync(monthDir)
          .filter(file => file.startsWith(month))
          .map(file => file.replace(".json", ""));
      res.json(days);
  } catch (error) {
      res.status(500).json({ error: "Failed to fetch days." });
  }
});

// 获取某天的JSON数据
router.get("/vtimgparms/:date", (req, res) => {
  const jsonRootDir = "L1X/imgInfo";
  const fullJsonRootDir = path.join(VT_IMG_PARM_DIR, jsonRootDir);
  try {
      const { date } = req.params;
      const year = date.split("-")[0];
      const filePath = path.join(fullJsonRootDir, year, `${date}.json`);
      if (!fs.existsSync(filePath)) {
          return res.status(404).json({ error: "Data not found." });
      }
      const jsonData = JSON.parse(fs.readFileSync(filePath, "utf8"));
      res.json(jsonData);
  } catch (error) {
      res.status(500).json({ error: "Failed to fetch data." });
  }
});

module.exports = router;